package com.times.demo.utils;

import lombok.SneakyThrows;
import javax.servlet.http.HttpServletRequest;
import java.util.Set;
import java.util.StringTokenizer;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @author chenhuanwei
 * @date 2019/12/4
 */
public class IpUtil {

    private static final Set<String> LOCALHOST_SET = Stream
            .of("127.0.0.1", "LOCALHOST", "0:0:0:0:0:0:0:1")
            .collect(Collectors.toSet());


    private static final String _255 = "(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)";
    private static final Pattern pattern = Pattern.compile("^(?:" + _255 + "\\.){3}" + _255 + "$");




    /**
     * 获取客户端IP
     */
    public static String getIpFromRequest(HttpServletRequest request) {
        String ip;
        boolean found = false;
        if ((ip = request.getHeader("x-forwarded-for")) != null) {
            StringTokenizer tokenizer = new StringTokenizer(ip, ",");
            while (tokenizer.hasMoreTokens()) {
                ip = tokenizer.nextToken().trim();
                if (isIPv4Valid(ip) && !isIPv4Private(ip)) {
                    found = true;
                    break;
                }
            }
        }
        if (!found) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }

    private static String longToIpV4(long longIp) {
        int octet3 = (int) ((longIp >> 24) % 256);
        int octet2 = (int) ((longIp >> 16) % 256);
        int octet1 = (int) ((longIp >> 8) % 256);
        int octet0 = (int) ((longIp) % 256);
        return octet3 + "." + octet2 + "." + octet1 + "." + octet0;
    }

    private static long ipV4ToLong(String ip) {
        String[] octets = ip.split("\\.");
        return (Long.parseLong(octets[0]) << 24) + (Integer.parseInt(octets[1]) << 16)
                + (Integer.parseInt(octets[2]) << 8) + Integer.parseInt(octets[3]);
    }

    private static boolean isIPv4Private(String ip) {
        long longIp = ipV4ToLong(ip);
        return (longIp >= ipV4ToLong("10.0.0.0") && longIp <= ipV4ToLong("10.255.255.255"))
                || (longIp >= ipV4ToLong("172.16.0.0") && longIp <= ipV4ToLong("172.31.255.255"))
                || longIp >= ipV4ToLong("192.168.0.0") && longIp <= ipV4ToLong("192.168.255.255");
    }

    private static boolean isIPv4Valid(String ip) {
        return pattern.matcher(ip).matches();
    }


    /**
     * 获取服务器IP
     */
    public static String getIpAddress() {
        return getIpAddress(HttpServletUtil.getRequest());
    }

    /**
     * 获取服务器IP
     * 访问方式有localhost、127.0.0.1、本地IP、映射IP
     */
    @SneakyThrows
    public static String getIpAddress(HttpServletRequest request) {
        String ip = request.getServerName();
        if (LOCALHOST_SET.contains(ip.toUpperCase())) {
            ip = getIpFromRequest(request);
        }
        return ip;
    }
}

